#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time: 2025/9/4

from fastapi import FastAPI, Request, Form
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from fastapi.responses import HTMLResponse, RedirectResponse
from pydantic import BaseModel
from typing import Optional

app = FastAPI(title="个人网站", description="我的个人网站", version="1.0.1")

# 挂载静态文件目录
app.mount("/static", StaticFiles(directory="static"), name="static")

# 设置模板目录
templates = Jinja2Templates(directory="templates")


# 模拟数据库 - 实际项目中可以使用真实数据库
class Project(BaseModel):
    id: int
    title: str
    description: str
    image_url: Optional[str] = None
    project_url: Optional[str] = None


projects_db = [
    Project(
        id=1,
        title="项目一",
        description="这是一个使用Python和FastAPI构建的Web应用程序",
        image_url="/static/images/project1.jpg",
        project_url="#"
    ),
    Project(
        id=2,
        title="项目二",
        description="一个使用React和Node.js构建的电子商务平台",
        image_url="/static/images/project2.jpg",
        project_url="#"
    ),
    Project(
        id=3,
        title="项目三",
        description="一个机器学习项目，用于预测房价",
        image_url="/static/images/project3.jpg",
        project_url="#"
    )
]


class ContactForm(BaseModel):
    name: str
    email: str
    message: str


# 路由定义
@app.get("/", response_class=HTMLResponse)
async def home(request: Request):
    return templates.TemplateResponse("index.html", {"request": request})


@app.get("/about", response_class=HTMLResponse)
async def about(request: Request):
    return templates.TemplateResponse("about.html", {"request": request})


@app.get("/projects", response_class=HTMLResponse)
async def projects(request: Request):
    return templates.TemplateResponse("projects.html", {"request": request, "projects": projects_db})


@app.get("/contact", response_class=HTMLResponse)
async def contact(request: Request):
    return templates.TemplateResponse("contact.html", {"request": request})


@app.post("/contact", response_class=HTMLResponse)
async def handle_contact(
        request: Request,
        name: str = Form(...),
        email: str = Form(...),
        message: str = Form(...)
):
    # 这里可以添加处理联系表单的逻辑，比如保存到数据库或发送邮件
    print(f"收到来自 {name} ({email}) 的消息: {message}")

    # 重定向到感谢页面或返回成功消息
    return templates.TemplateResponse(
        "contact.html",
        {"request": request, "success_message": "感谢您的留言！我会尽快回复。"}
    )


if __name__ == "__main__":
    import uvicorn

    uvicorn.run(app, host="0.0.0.0", port=8000)